package com.dingpeikeji.quickdeer.modules.interceptor;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.base.web.CookieUtils;
import com.dingpeikeji.quickdeer.modules.base.web.FInfoController;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;

import net.sf.json.JSONObject;

public class FrontBaseInterceptor implements HandlerInterceptor {
	
	public static final String FRONT_BACK_URL_IN_SESSION = "FRONT_BACK_URL_IN_SESSION";
	public static final String FRONT_USER_IN_SESSION = "front_user";
	@Autowired
	private FrontUserService frontUserService;
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		User user = (User)request.getSession().getAttribute(FSysController.FRONT_USER_IN_SESSION);
		if(user == null) {
			String path = request.getContextPath();
			String basePath = new String();
			if (request.getServerPort() == 80) {
				basePath = request.getScheme() + "://"
						+ request.getServerName();
			}else{
				basePath = request.getScheme() + "://"
						+ request.getServerName() + ":" + request.getServerPort();
			}
			// 跳过一些页面
			if(!request.getRequestURI().contains("user/forgetPwd")) {
				String backPage = basePath + request.getRequestURI()+"?"; // 拦截的访问的路径，保存到session中
				//2.3获取指定的cookie
				Cookie[] cookies = request.getCookies();
				Cookie cookie = CookieUtils.findCookie(cookies, "autoLogin");
				//判断cookie是否为空
				//若不为空 获取值(username和passowrd) 调用serivce完成登录  判断user是否为空 不为空 放入session
				if (cookie!=null) {
					String value = cookie.getValue();// aaa#111
					// 获得用户名和密码:
					String username = value.split("#")[0];
					String password = value.split("#")[1];
					// 去数据库进行查询:
					user = frontUserService.findUser(username,password);
					if(user!=null){
						//将user放入session中
						request.getSession().setAttribute(FRONT_USER_IN_SESSION, user);
					}
				}
				@SuppressWarnings("unchecked")
				Map<String,Object> param = request.getParameterMap();
				if(param!=null) {
					Set<String> keys = param.keySet();
					Iterator<String> it = keys.iterator();
					while(it.hasNext()){
						String key = it.next();
						String[] values = (String[])param.get(key);
						if(values != null) {
							String p = "&"+key+"=";
							for(int i=0;i<values.length;i++) {
								if(i!=values.length){
									p += new String(values[i].getBytes("utf-8"),"iso-8859-1");
								} else {
									p += new String(values[i].getBytes("utf-8"),"iso-8859-1")+",";
								}
							}
							backPage += p;
						}
					}
				}
				request.getSession().setAttribute(FRONT_BACK_URL_IN_SESSION, backPage);
				String contextPath = "";
				if (basePath.contains("localhost")) {
					contextPath = request.getContextPath() +"/login.jsp?backUrl="+backPage;
				}else{
					contextPath = "https://www.xiakeyueche.com/login.jsp?backUrl="+backPage;
				}
				response.sendRedirect(contextPath);
			}
			return false;
		}
		return true;
	}

}
